# -*- coding:utf-8 -*-
"""
    异常网络检测部分
"""
@config(alias="ip", enable=True)
def check_network_abroad(option):
    """境外IP的链接"""
    suspicious = False
    if 1:
        shell_process = os.popen(
            "netstat -anp 2>/dev/null| grep ESTABLISHED | awk '{print $1\" \"$5\" \"$7}'").read().splitlines()
        for nets in shell_process:
            netinfo = nets.strip().split(' ')
            protocol = netinfo[0]
            remote_ip, remote_port = netinfo[1].replace("\n", "").split(":")
            pid, pname = netinfo[2].replace("\n", "").split("/")
            if check_ip(remote_ip):
                save_result("境外IP网络链接", "进程 %s 境外IP %s 通过%s于主机建立链接"%(pname, remote_ip, protocol), "m")
                suspicious = True
        return suspicious
    else:
        return suspicious

@config(alias="port", enable=True)
def check_net_suspicious(option):
    """可疑端口的链接"""
    suspicious  = False
    if 1:
        shell_process = os.popen(
            "netstat -anp 2>/dev/null| grep ESTABLISHED | awk '{print $1\" \"$5\" \"$7}'").read().splitlines()
        if not len(shell_process):
            monitoring_objects_num("port")
            return suspicious
        for malware in port_malware:
            for nets in shell_process:
                monitoring_objects_num("port")
                netinfo = nets.strip().split(' ')
                protocol = netinfo[0]
                try:
                    remote_ip, remote_port = netinfo[1].replace("\n", "").split(":")
                    pidPname =  netinfo[2].replace("\n", "").split("/")
                    pid, pname = pidPname[0], pidPname[-1]
                except:
                    remote_port = ""

                if malware['port'] == remote_port:
                    save_result("可疑端口的链接", "进程名: %s, pid: %s, 主机链接了远程IP: %s的可疑的端口:%s 此端口通常被用于:%s"%
                                (pname, pid, remote_ip, remote_port, malware["description"]), 'm')
                    suspicious = True
                    break
        return suspicious
    else:
        return suspicious

@config(alias="promisc", enable=True)
def check_promisc(option):
    """网卡混杂模式检测"""
    suspicious = False
    if 1:
        shell_process = os.popen("ifconfig 2>/dev/null| grep PROMISC | grep RUNNING").read().splitlines()
        monitoring_objects_num("promisc") # 网卡混杂模式有且仅有一个检测项
        if len(shell_process) > 0:
            save_result("网卡混杂模式检测", "网卡混杂模式信息%s"%(shell_process), "l")
            suspicious = True
        return suspicious
    else:
        return suspicious, malice

